from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout, update_session_auth_hash
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.http import require_http_methods
from django.urls import reverse
from django.contrib import messages
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
import os

User = get_user_model()


@csrf_protect
@require_http_methods(["GET", "POST"])
def login_view(request):
    """
    用户登录视图 - 支持邮箱或用户名登录
    """
    if request.method == 'POST':
        identifier = request.POST.get('identifier')
        password = request.POST.get('password')

        if not identifier or not password:
            return JsonResponse({'success': False, 'message': '请填写所有字段'})

        # 尝试使用用户名或邮箱进行认证
        user = authenticate(request, username=identifier, password=password)
        
        # 如果用户名认证失败，尝试使用邮箱认证
        if user is None:
            try:
                user_obj = User.objects.get(email=identifier)
                user = authenticate(request, username=user_obj.username, password=password)
            except User.DoesNotExist:
                pass

        if user is not None:
            login(request, user)
            # 获取重定向URL，默认为首页
            next_url = request.POST.get('next') or request.GET.get('next') or '/index/'
            return JsonResponse({
                'success': True, 
                'message': '登录成功',
                'next_url': next_url
            })
        else:
            # 检查用户是否存在但密码错误
            username_exists = User.objects.filter(username=identifier).exists()
            email_exists = User.objects.filter(email=identifier).exists()
            
            if username_exists or email_exists:
                return JsonResponse({'success': False, 'message': '密码错误'})
            else:
                return JsonResponse({'success': False, 'message': '账号不存在，请先注册'})

    return render(request, 'accounts/login.html')


@csrf_protect
@require_http_methods(["GET", "POST"])
def register_view(request):
    """
    用户注册视图 - 支持用户名或邮箱二选一登录
    """
    if request.method == 'POST':
        username = request.POST.get('username', '').strip()
        email = request.POST.get('email', '').strip()
        password = request.POST.get('password')
        confirm_password = request.POST.get('confirmPassword')
        nickname = request.POST.get('nickname', '').strip()  # 获取昵称，如果没有提供则为空

        # 清理空字符串为None
        username = username if username else None
        email = email if email else None
        nickname = nickname if nickname else None

        # 验证输入 - 用户名和邮箱至少填写一个
        if (not username and not email) or not password:
            return JsonResponse({'success': False, 'message': '用户名和邮箱至少填写一个，密码必填'})

        # 验证密码确认
        if password != confirm_password:
            return JsonResponse({'success': False, 'message': '密码和确认密码不匹配'})

        # 统一检查重复性 - 避免重复检查
        existing_checks = []
        
        if username:
            if User.objects.filter(username=username).exists():
                return JsonResponse({'success': False, 'message': '用户名已存在，请选择其他用户名'})
        
        if email:
            if User.objects.filter(email=email).exists():
                return JsonResponse({'success': False, 'message': '邮箱已被注册，请使用其他邮箱'})
            # 如果只提供邮箱，还需检查是否被用作用户名
            if not username and User.objects.filter(username=email).exists():
                return JsonResponse({'success': False, 'message': '该邮箱已被注册为用户名'})

        # 创建用户
        try:
            # 根据填写的信息创建用户
            if username and email:
                # 同时提供了用户名和邮箱
                user = User.objects.create_user(
                    username=username, 
                    email=email, 
                    password=password
                )
                user.nickname = nickname if nickname else username
            elif username:
                # 只提供了用户名
                user = User.objects.create_user(
                    username=username, 
                    password=password
                )
                user.email = None  # 显式设置为 None
                user.nickname = nickname if nickname else username
            else:
                # 只提供了邮箱，使用邮箱作为用户名
                user = User.objects.create_user(
                    username=email, 
                    email=email, 
                    password=password
                )
                user.nickname = nickname if nickname else (email.split('@')[0] if email else 'user')  # 使用邮箱的用户名部分作为昵称
            
            # 统一保存用户
            user.save()
            return JsonResponse({'success': True, 'message': '注册成功！正在跳转到登录页面...'})
            
        except Exception as e:
            # 提供更好的错误信息
            error_msg = str(e).lower()
            if 'unique constraint' in error_msg:
                if 'username' in error_msg:
                    return JsonResponse({'success': False, 'message': '用户名已存在，请选择其他用户名'})
                elif 'email' in error_msg:
                    return JsonResponse({'success': False, 'message': '邮箱已被注册，请使用其他邮箱'})
                else:
                    return JsonResponse({'success': False, 'message': '注册信息重复，请检查后重试'})
            else:
                return JsonResponse({'success': False, 'message': f'注册失败，请稍后重试'})

    return render(request, 'accounts/register.html')


@login_required
def logout_view(request):
    """
    用户登出视图
    """
    logout(request)
    return redirect('/index/')


@login_required
@csrf_protect
@require_http_methods(["GET", "POST"])
def profile_view(request):
    """
    个人中心视图 - 显示和修改个人信息
    """
    if request.method == 'POST':
        user = request.user
        username = request.POST.get('username', '').strip()
        email = request.POST.get('email', '').strip()
        nickname = request.POST.get('nickname', '').strip()
        head_img = request.FILES.get('head_img')
        
        # 验证输入
        if not username and not email:
            return JsonResponse({'success': False, 'message': '用户名和邮箱至少填写一个'})
        
        # 检查用户名是否被其他用户使用
        if username and User.objects.filter(username=username).exclude(id=user.id).exists():
            return JsonResponse({'success': False, 'message': '用户名已存在'})
        
        # 检查邮箱是否被其他用户使用
        if email and User.objects.filter(email=email).exclude(id=user.id).exists():
            return JsonResponse({'success': False, 'message': '邮箱已被注册'})
        
        try:
            # 更新用户信息
            if username:
                user.username = username
            if email:
                user.email = email
            if nickname:
                user.nickname = nickname
            
            # 处理头像上传
            if head_img:
                # 删除旧头像（除非是默认头像）
                if user.head_img and 'default.jpg' not in user.head_img.name:
                    if default_storage.exists(user.head_img.name):
                        default_storage.delete(user.head_img.name)
                
                # 保存新头像
                user.head_img = head_img
            
            user.save()
            return JsonResponse({'success': True, 'message': '个人信息更新成功'})
            
        except Exception as e:
            return JsonResponse({'success': False, 'message': f'更新失败：{str(e)}'})
    
    return render(request, 'accounts/profile.html', {'user': request.user})


@login_required
@csrf_protect
@require_http_methods(["GET", "POST"])
def change_password_view(request):
    """
    修改密码视图
    """
    if request.method == 'POST':
        user = request.user
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        confirm_password = request.POST.get('confirm_password')
        
        # 验证输入
        if not old_password or not new_password or not confirm_password:
            return JsonResponse({'success': False, 'message': '请填写所有字段'})
        
        # 验证旧密码
        if not user.check_password(old_password):
            return JsonResponse({'success': False, 'message': '旧密码错误'})
        
        # 验证新密码确认
        if new_password != confirm_password:
            return JsonResponse({'success': False, 'message': '新密码和确认密码不匹配'})
        
        try:
            # 更新密码
            user.set_password(new_password)
            user.save()
            
            # 更新会话，避免用户被登出
            update_session_auth_hash(request, user)
            
            return JsonResponse({'success': True, 'message': '密码修改成功'})
            
        except Exception as e:
            return JsonResponse({'success': False, 'message': f'密码修改失败：{str(e)}'})
    
    return render(request, 'accounts/change_password.html')